package shapewar.engine.model;

import shapewar.conf.Conf;
import shapewar.engine.calc.Pos;
import shapewar.engine.intefac.IHittable;
import shapewar.engine.intefac.ITank;
import shapewar.engine.intefac.Regedit;
import shapewar.engine.model.abst.ModelAdapter;
import shapewar.engine.presenter.Presenter;

public class Bullet extends ModelAdapter {
	public Tank father;
	private boolean able = true;
	private boolean target_set_mark = false;
	public Bullet(Presenter pst, int id,int key, Tank father) {
		super(pst, id, father._x, father._y, Conf.bullet_radium, Conf.depth_bullet);
		this.father = father;
		setKey(key);
	}
	
	@Override
	public void init() {
		speed = Conf.bullet_speed;
		this.r = Conf.bullet_radium;
		pst.bridge.addView(pst.bridge.createBulletView(this));
		pst.regist(this, Regedit.Map4Bullet,Regedit.IRepeat4Bullet,Regedit.IView);
		able = getFather().isPlayer();
	}
	
	@Override
	public void destory() {
		pst.bridge.removeView(getView());
		pst.registoff(this, Regedit.Map4Bullet,Regedit.IRepeat4Bullet,Regedit.IView);
	}
	
	@Override
	public void die() {
		pst.bridge.createBulletDieEffect(this);
		destory();
	}
	
	@Override
	public void repeat() {
		Pos tmpPos = new Pos(_x,_y);
		calcer.move(tmpPos, _rotation, speed);
		
		//Bullet Hit Walls & Bullet hit Edge
		if(calcer.limitPos(tmpPos, this)){
			able = false;
			destory();
			return;
		}else{
			setPos(tmpPos);
		}
		
		if(calcer.calcDistance(tmpPos, father.getPos())>Conf.visible_area_radium){
			destory();
			return;
		}
		
		if(able){
			//Bullet hit Protector
			IHittable protector = calcer.hitProtectors(this);
			if(protector!=null) {
				if(!((Tank)protector.getFather()).isInSuperTime()){
					getFather().getUser().requireProtectorMinus((ITank)protector.getFather(), getFather(), getKey());
					die();
					return;
				}
			}
			//Bullet hit Tank
			Tank tank = (Tank) calcer.hitTanks(this);
			if(tank!=null){
				if(!((Tank)tank).isInSuperTime()){
					getFather().getUser().requireDie(tank, getFather(), getKey(), tank.getProtector().count);
					die();
					return;
				}
			}
		}
		//Bullet hit Protector
		IHittable protector = calcer.hitProtectors(this);
		if(protector!=null) {
			if(!((Tank)protector.getFather()).isInSuperTime()){
				die();
				return;
			}
		}
		//Bullet hit Tank
		Tank tank = (Tank) calcer.hitTanks(this);
		if(tank!=null){
			if(!((Tank)tank).isInSuperTime()){
				die();
				return;
			}
		}
	}
	
	@Override
	public void setTargetPos(Pos pos) {
		if(!target_set_mark){
			target_set_mark = true;
			super.setTargetPos(pos);
		}
	}
	
	@Override
	public void moveTo(Pos pos) {
		super.moveTo(pos);
		_x = _x + 2 * Conf.tank_size_factor * (float)Math.cos(_rotation * Math.PI / 180);
		_y = _y - 2 * Conf.tank_size_factor * (float)Math.sin(_rotation * Math.PI / 180);
	}
	
	public Tank getFather(){
		return father;
	}
	
	@Override
	public String toString() {
		return "Protector(x,y = "+pos+"),targetx,target_y = "+target+",rotation = "+_rotation+")";
	}
	
}
